﻿using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using NOSDC.Repositories;
using NOSDC.Pocos;

namespace NOSDC.Areas.Admin.Controllers
{
    public class SponsorController : BaseController
    {
        private readonly SponsorRepository _repository;

        public SponsorController()
        {
            _repository = new SponsorRepository();
        }

        // GET: /Admin/Sponsor/
        public ActionResult Index()
        {
            return View(_repository.GetAllSponsors());
        }

  
        // GET: /Admin/Sponsor/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }


        // GET: /Admin/Sponsor/Create
        public ActionResult Create()
        {
            var sponsor = new Sponsor();
            return View(sponsor);
        } 

        // POST: /Admin/Sponsor/Create
        [HttpPost, ValidateInput(false)]
        public ActionResult Create(Sponsor sponsor)
        {
            try
            {
                // TODO: Add insert logic here
                if (ModelState.IsValid)
                {
                    _repository.AddSponsor(sponsor);
                }

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        

        // GET: /Admin/Sponsor/Edit/5
        public ActionResult Edit(int id)
        {
            
            return View(_repository.GetSponsorByID(id));
        }


        // POST: /Admin/Sponsor/Edit/5
        [HttpPost, ValidateInput(false)]
        public ActionResult Edit(Sponsor s)
        {
            
                _repository.UpdateSponsor(s);
                return RedirectToAction("Index");
         
        }

        // POST: /Admin/Sponsor/Delete/5
        public ActionResult Delete(int id)
        {
            _repository.DeleteSponsor(id);
            return RedirectToAction("Index");
        }

        public string UploadSponsorLogo(HttpPostedFileBase fileData)
        {
            try
            {
                var path = Server.MapPath("~/UploadedFiles");
                var file = Path.Combine(path, Path.GetFileName(fileData.FileName));
                fileData.SaveAs(file);

                return String.Format("Your file {0} has been uploaded", Path.GetFileName(fileData.FileName));
            }
            catch(Exception)
            {
                return "An error occurred. :(";
            }
        }
    }
}
